import Vue from 'vue'
import VueRouter from 'vue-router'

import store from '@/store'

import Login from '@/views/login'
import Register from '@/views/register'
import Systems from '@/views/Systems'

const Layout = () => import('@/views/Systems/Layout')
const Buy = () => import('@/views/Systems/Buy')
const HistoryGoods = () => import('@/views/Systems/HistoryGoods')
const Sale = () => import('@/views/Systems/Sale')
const Employee = () => import('@/views/Systems/Employee')
const Stock = () => import('@/views/Systems/Stock')

const Notice = () => import('@/views/Systems/Notice')

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/systems'
  },
  {
    path: '/login',
    component: Login
  },
  {
    path: '/register',
    component: Register
  },
  {
    path: '/systems',
    name: '进销存',
    component: Systems,
    redirect: '/layout',
    children: [
      {
        path: '/layout',
        name: '进销存',
        component: Layout
      },
      {
        path: '/buy',
        component: Buy
      },
      {
        path: '/history_goods',
        component: HistoryGoods
      },
      {
        path: '/sale',
        component: Sale
      },
      {
        path: '/employee',
        component: Employee
      },
      {
        path: '/stock',
        component: Stock
      },
      {
        path: '/notice',
        component: Notice
      },
      {
        path: '/warehouse',
        component: () => import('@/views/Systems/Warehouse')
      }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 权限路径
const authUrls = ['/systems', '/layout', '/history_goods', '/sale', '/employee', '/stock', '/buy']

router.beforeEach((to, from, next) => {
  // 如果是非权限路径直接放行
  if (!authUrls.includes(to.path)) {
    next()
    return
  }

  // 如果是权限路径需要判断token
  const token = store.getters.token
  if (token) {
    next()
  } else {
    next('/login')
    location.reload()
  }
})

export default router
